<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改收款单')" />
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-receivemoney-edit" th:object="${receiveMoneyVo.receiveMoney}">
            <h4 class="form-header h4">收款单信息</h4>
            <input name="id" th:value="${receiveMoneyVo.receiveMoney.id}" type="hidden">
            <div class="form-group">    
                <label class="col-sm-3 control-label">付款单编号：</label>
                <div class="col-sm-8">
                    <input name="orderCode" th:value="${receiveMoneyVo.receiveMoney.orderCode}" class="form-control" type="text" readonly>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">客户：</label>
                <div class="col-sm-8">
                    <div class="input-group">
                        <input id="customerId" name="customerId" type="hidden" th:value="${receiveMoneyVo.receiveMoney.customerId}" >
                        <input id="customerName" name="customerName" class="form-control" type="text" onclick="selectCustomer()" th:value="${receiveMoneyVo.receiveMoney.customerName}"  readonly required>
                        <span class="input-group-addon"><i class="fa fa-search"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">资金业务类型：</label>
                <div class="col-sm-8">
                    <select name="capitalType" class="form-control" th:with="type=${@dict.getType('capital_type')}">
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{capitalType}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">结算方式：</label>
                <div class="col-sm-8">
                    <select name="capitalSettlementWay" class="form-control" th:with="type=${@dict.getType('capital_settlement_way')}">
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{capitalSettlementWay}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">收款日期：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="orderDate" th:value="${#dates.format(receiveMoneyVo.receiveMoney.orderDate, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">收款银行：</label>
                <div class="col-sm-8">
                    <input name="receiveBank" th:value="${receiveMoneyVo.receiveMoney.receiveBank}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">收款账户：</label>
                <div class="col-sm-8">
                    <input name="receiveAccount" th:value="${receiveMoneyVo.receiveMoney.receiveAccount}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">收款金额：</label>
                <div class="col-sm-8">
                    <input id="receiveAmounts" name="receiveAmounts" th:value="${receiveMoneyVo.receiveMoney.receiveAmounts}" class="form-control" type="number" step="0.01" readonly required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">备注：</label>
                <div class="col-sm-8">
                    <textarea name="remark" class="form-control" maxlength="200">[[*{remark}]]</textarea>
                </div>
            </div>

            <h4 class="form-header h4">收款单子信息</h4>
            <div class="row">
                <div class="col-sm-12">
                    <button type="button" class="btn btn-white btn-sm" onclick="sub.delRow()"><i class="fa fa-minus"> 删除</i></button>
                    <div class="col-sm-12 select-table table-striped">
                        <table id="bootstrap-table"></table>
                    </div>
                </div>
            </div>
        </form>

        <div class="row">
            <div class="col-sm-offset-5 col-sm-10">
                <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭 </button>
            </div>
        </div>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <script th:inline="javascript">
        var prefix = ctx + "bill/receivemoney";
        $("#form-receivemoney-edit").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.saveTab(prefix + "/edit", $('#form-receivemoney-edit').serialize());
            }
        }

        $("input[name='orderDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $(function() {
            var options = {
                data:[[${receiveMoneyVo.items}]],
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                columns: [{
                    checkbox: true
                },
                    {
                        field: 'index',
                        align: 'center',
                        title: "序号",
                        formatter: function (value, row, index) {
                            var columnIndex = $.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumber(index));
                            return columnIndex + $.table.serialNumber(index);
                        }
                    },
                    {
                        field: 'id',
                        align: 'center',
                        title: 'id',
                        visible: false
                    },
                    {
                        field: 'saleCode',
                        align: 'center',
                        title: '销售单',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' name='items[%s].saleCode' value='%s' readonly>", index, value);
                            var saleId = $.common.sprintf("<input type='hidden' name='items[%s].saleId' value='%s'>", index, row.saleId);//销售单id 隐藏域
                            return html + saleId;
                        }
                    },
                    {
                        field: 'noReceiveAmount',
                        align: 'center',
                        title: '应收金额',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' name='items[%s].noReceiveAmount' value='%s' readonly>", index, value);
                            return html;
                        }
                    },
                    {
                        field: 'receiveAmount',
                        align: 'center',
                        title: '本次收款',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='number' step='0.01' name='items[%s].receiveAmount' value='%s' required onchange='reloadRowReceiveAmountData("+index+","+row.noReceiveAmount+",this)'>", index, value);
                            return html;
                        }
                    },
                    {
                        field: 'remark',
                        align: 'center',
                        title: '备注',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' name='items[%s].remark' value='%s'>", index, value);
                            return html;
                        }
                    }]
            };
            $.table.init(options);
        });

        /**
         * 修改计算金额
         * */
        function reloadRowReceiveAmountData(index,noReceiveAmount, obj) {
            if ($.common.isNotEmpty(index)) {
                var receiveAmount = $(obj).val();
                var regu = /^\d+(\.{0,1}\d{1,2})?$/;//非负浮点数（正浮点数 + 0）
                if ($.common.isEmpty(receiveAmount) || !regu.test(receiveAmount)) {
                    $.modal.alertWarning("不能为空或输入的不是非负浮点数(只能保留2位)");
                    return;
                }
                //判断金额不能大于应付金额
                if(parseFloat(noReceiveAmount)<parseFloat(receiveAmount)){
                    $.modal.alertWarning("收款金额不能大于应收金额");
                    return;
                }
                //更新字段数据
                updateCell(index,receiveAmount);
            }
        }

        //更新指定的列数据
        function updateCell(index, receiveAmount) {//更新表格数据
            var _data = new Object();//某行数据
            _data.receiveAmount = receiveAmount;
            $("#" + table.options.id).bootstrapTable("updateRow", {index: index, row: _data});
            //总计
            calculate()
        }


        /**
         * 计算合计商品各项值之和
         */
        function calculate() {
            var data = $("#" + table.options.id).bootstrapTable('getData');//查询表格所有数据
            console.info(JSON.stringify(data));
            var totalAmount = 0;
            $.each(data, function (index, obj) {
                if($.common.isNotEmpty(obj.receiveAmount)) {
                    totalAmount = numAdd(totalAmount, obj.receiveAmount);
                }
            });
            $('#receiveAmounts').val(totalAmount);
        }

        /* 选择客户 */
        var customerPrefix = ctx + "basic/customer"
        function selectCustomer() {
            var url = customerPrefix + '/selectCustomer';
            var options = {
                title: '选择客户',
                url: url,
                callBack: doSubmitCustomer
            };
            $.modal.openOptions(options);
        }

        function doSubmitCustomer(index, layero) {
            var iframeWin = layero.find("iframe")[0].contentWindow.$.table;
            var rows = iframeWin.selectFirstColumns();
            if (rows.length == 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }
            var customerId = rows.join();
            $('#customerId').val(customerId)
            var customerName=iframeWin.selectColumns("customerName").join();
            $('#customerName').val(customerName)

            //重置子表
            sub.removeAllRow();
            //根据客户Id获取子表数据
            getSaleOrderList(customerId)

            $.modal.close(index);
        }

        //获取子表数据
        function getSaleOrderList(customerId){
            var data = {"customerId":customerId};
            var config = {
                url: prefix + "/item/selectSaleOrderAjaxList",
                type: "post",
                dataType: "json",
                data: data,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        $.each(result.data,function(index,value){
                            var row = {
                                id: "",
                                saleId: value.saleId,
                                saleCode: value.saleCode,
                                noReceiveAmount: value.noReceiveAmount,
                                payAmount: 0,
                                remark:""
                            }
                            sub.addRow(row);
                        });
                    }else {
                        $.modal.alertError(result.msg);
                    }
                    $.modal.closeLoading();
                }
            };
            $.ajax(config)
        }


    </script>
</body>
</html>